/**
 * @filename:StkOtherInServiceImpl Feb 5, 2025
 * @project Wonder Vue Admin Api  1.1.0
 * Copyright(c) 2022 Wonder Co. Ltd. 
 * All right reserved. 
 */
package com.wonder.app.service.impl;

import cn.hutool.core.date.DateTime;
import com.vtuzx.core.bean.dto.VtuzxMap;
import com.vtuzx.core.utils.VtuzxUtil;
import com.wonder.admin.service.IVtuzxKingdeeService;
import com.wonder.app.domain.*;
import com.wonder.app.mapper.StkOtherInDao;
import com.wonder.app.mapper.StkOtherInDeatilDao;
import com.wonder.app.service.*;
import com.wonder.app.request.StkOtherInRequest;
import com.wonder.bean.kingdee.VtuzxKingdeeCloudClient;
import com.wonder.bean.kingdee.xqc.VtuzxArrayList;
import com.wonder.common.utils.StringUtils;
import com.wonder.common.utils.MessageUtils;
import com.wonder.common.common.AjaxResult;

import java.util.*;

import com.wonder.constant.BillType;
import com.wonder.constant.IXqcConst;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

/**   
 * @Description:TODO(其他入库单服务实现)
 *
 * @version: 1.1.0
 * @author: Wonder
 * 
 */
@Service
public class StkOtherInServiceImpl  extends ServiceImpl<StkOtherInDao, StkOtherIn> implements StkOtherInService  {
	/**
	 * Logger
	 */
	private static final Logger _logger = LoggerFactory.getLogger(StkOtherInServiceImpl.class);

	@Autowired
	private IVtuzxKingdeeService vtuzxKingdeeService;

	@Autowired
	private YzjService yzjService;

	@Autowired
	private StkOtherInService stkOtherInService;
	@Autowired
	private StkOtherInDeatilService stkOtherInDeatilService;
	@Autowired
	private StkOtherInDao stkOtherInDao;
	@Autowired
	private StkOtherInDeatilDao stkOtherInDeatilDao;


	@Autowired
	private SyncKingdeeOrderService syncKingdeeOrderService;



    /**
     * 验证其他入库单信息
     * 
     * @param stkOtherIn
     * @param type
     * @return String
     */
    @Override
    public String validate(StkOtherIn stkOtherIn,String type){
    
    
       return "";
    }
    
    
    /**
	 * Description:其他入库单分页返回
	 * @param request //检索条件
	 * @param page //分页参数
	 * @return IPage<StkOtherIn>   //分页记录
	 */
	@Override 
	public IPage<StkOtherIn> selectList(StkOtherInRequest request, Page<StkOtherIn> page){
	    LambdaQueryWrapper<StkOtherIn> lambdaQueryWrapper = new LambdaQueryWrapper<>();
	    
	    if (null != request.getId()) {
	       lambdaQueryWrapper.eq(StkOtherIn::getId, request.getId());
	      }
		if (StringUtils.hasText(request.getBillNo())) {
			lambdaQueryWrapper.like(StkOtherIn::getBillNo, request.getBillNo());
		}

		if (StringUtils.hasText(request.getWeightNo())) {
			lambdaQueryWrapper.like(StkOtherIn::getWeightNo, request.getWeightNo());
		}

		if (request.getDate() != null) {
			Date[] fCREATEDATE = request.getDate();
			if (fCREATEDATE.length > 0) {
				// 设置开始时间为当天的零点
				Calendar startCalendar = Calendar.getInstance();
				startCalendar.setTime(fCREATEDATE[0]);
				startCalendar.set(Calendar.HOUR_OF_DAY, 0);
				startCalendar.set(Calendar.MINUTE, 0);
				startCalendar.set(Calendar.SECOND, 0);
				startCalendar.set(Calendar.MILLISECOND, 0);
				Date startDate = startCalendar.getTime();
				lambdaQueryWrapper.ge(StkOtherIn::getDate, startDate);
			}
			if (fCREATEDATE.length == 2) {
				// 设置结束时间为当天的24点
				Calendar endCalendar = Calendar.getInstance();
				endCalendar.setTime(fCREATEDATE[1]);
				endCalendar.set(Calendar.HOUR_OF_DAY, 23);
				endCalendar.set(Calendar.MINUTE, 59);
				endCalendar.set(Calendar.SECOND, 59);
				endCalendar.set(Calendar.MILLISECOND, 999);
				Date endDate = endCalendar.getTime();
				lambdaQueryWrapper.le(StkOtherIn::getDate, endDate);
			}
		}
        
		lambdaQueryWrapper.orderByDesc(StkOtherIn::getId);	
		Page<StkOtherIn> selectPage = this.baseMapper.selectPage(page, lambdaQueryWrapper);
		return selectPage;
    }

	/**
	 * receive详情
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@Override
	public Map<String, Object> getStkOtherInDetail(Map<String, Object> map) throws Exception {
		String billNo = map.get("billNo").toString();
		StkOtherIn stkotherinform = stkOtherInDao.selectOne(new LambdaQueryWrapper<StkOtherIn>()
				.eq(StkOtherIn::getBillNo,billNo));
		if (null == stkotherinform){
			throw new RuntimeException("单号错误请重试");
		}
		List<StkOtherInDeatil> stkotherinList = stkOtherInDeatilDao.selectList(new LambdaQueryWrapper<StkOtherInDeatil>()
				.eq(StkOtherInDeatil::getBillNo,billNo));
		Map<String,Object> data = new HashMap<>();
		data.put("data",stkotherinform);
		data.put("dataList",stkotherinList);
		return data;
	}

	@Override
	public Map<String, Object> getOtherInList(Map<String, Object> map) {
		int pageIndex = VtuzxUtil.getInt(map,"pageIndex");
		int pageSize = VtuzxUtil.getInt(map,"pageSize");
		String billNo = VtuzxUtil.getString(map,"billNo");//订单号
		List<StkOtherIn> dataList = stkOtherInDao.getOtherInList(pageSize,pageIndex * pageSize,billNo);
		Map<String,Object> data = new HashMap<>();
		data.put("dataList",dataList);
		return data;
	}

	@Override
	public boolean auditOtherIn(Long user_id, String userName, Map<String, Object> map) throws Exception {
		String billNo = VtuzxUtil.getString(map,"billNo");
		List<Map<String,Object>> detailList = VtuzxUtil.getObject(map,"dataList");
		Map<String,Object> dataMap = new HashMap<>();//key:单号+id.val:仓库，仓位，仓库名称
		for (Map<String,Object> data : detailList){
			int id = VtuzxUtil.getInt(data,"id");
			String detailNo = VtuzxUtil.getString(data,"billNo");
			String stockNo = VtuzxUtil.getString(data,"stockNo");
			String stockName = VtuzxUtil.getString(data,"stockName");
			String locationNo = VtuzxUtil.getString(data,"locationNo");
			boolean isLocation = VtuzxUtil.getBoolean(data,"isLocation");
			List<String> locationList = VtuzxUtil.getObject(data,"locationList");

			if (VtuzxUtil.isEmpty(stockNo)){
				throw new RuntimeException("请录入仓库");
			}
			if (isLocation  && VtuzxUtil.isEmpty(locationNo)){
				throw new RuntimeException("请录入仓位");
			}
			if (null != locationList ){
				if (!locationList.contains(locationNo)){
					throw new RuntimeException("仓位不属于当前仓库，请重试");
				}
			}

			Map<String,Object> stockMap =new HashMap<>();
			stockMap.put("stockName",stockName);
			stockMap.put("stockNo",stockNo);
			stockMap.put("locationNo",locationNo);
			dataMap.put(detailNo + id,stockMap);
		}
		StkOtherIn stkOtherIn = stkOtherInDao.selectOne(new LambdaQueryWrapper<StkOtherIn>()
				.eq(StkOtherIn::getBillNo,billNo));
		List<StkOtherInDeatil> otherDetailList = stkOtherInDeatilDao.selectList(new LambdaQueryWrapper<StkOtherInDeatil>()
				.eq(StkOtherInDeatil::getBillNo,billNo));

		//数据库添加仓位信息
		for (StkOtherInDeatil detail : otherDetailList){
			String billNo1 = detail.getBillNo();
			Long id = detail.getId();
			Map<String,Object> stockMap = VtuzxUtil.getObject(dataMap,billNo1 + id);
			String locationNo = VtuzxUtil.getString(stockMap,"locationNo");
			String stockNo = VtuzxUtil.getString(stockMap,"stockNo");
			String stockName = VtuzxUtil.getString(stockMap,"stockName");
			detail.setLocationNo(locationNo);
			detail.setLocationName(locationNo);
			detail.setStockName(stockName);
			detail.setStockNo(stockNo);
		}
		stkOtherInDeatilService.saveOrUpdateBatch(otherDetailList);

		stkOtherIn.setStatus("audit");
		stkOtherIn.setAuditTime(new DateTime());
		stkOtherIn.setAuditUserName(userName);
		boolean res = stkOtherInService.saveOrUpdate(stkOtherIn);
		try {
			syncKingdeeOrderService.syncOtherIn(user_id,userName,stkOtherIn,otherDetailList);
		}catch (Exception e){
			_logger.info(e.getMessage());
			throw new RuntimeException(e.getMessage());
		}
		return res;
	}

	@Override
	public Map<String, Object> getOtherInDetail(Map<String, Object> map) throws Exception {
		String billNo = map.get("billNo").toString();
		StkOtherIn stkotherinform = stkOtherInDao.selectOne(new LambdaQueryWrapper<StkOtherIn>()
				.eq(StkOtherIn::getBillNo,billNo)
				.eq(StkOtherIn::getStatus,"save"));
		if (null == stkotherinform){
			throw new RuntimeException("单号错误请重试");
		}
		List<StkOtherInDeatil> stkotherinList = stkOtherInDeatilDao.selectList(new LambdaQueryWrapper<StkOtherInDeatil>()
				.eq(StkOtherInDeatil::getBillNo,billNo));
		List<Map<String, Object>> stockList = selectStcokList();

		for (StkOtherInDeatil otherInDeatil : stkotherinList){
			if (null != otherInDeatil.getStockNo()){
				String stockNo = otherInDeatil.getStockNo();
				//金蝶查询当前仓库是否启用仓位
				Boolean aBoolean = stockIsLoc(stockNo);
				//查询仓库向下的仓位集合
				if (aBoolean){
					List<String> locationList = getlocationList(stockNo);
					otherInDeatil.setLocationList(locationList);
				}
				otherInDeatil.setIsLocation(aBoolean);
				otherInDeatil.setStockList(stockList);
			}

		}
		Map<String,Object> data = new HashMap<>();
		data.put("data",stkotherinform);
		data.put("dataList",stkotherinList);
		return data;
	}

	@Override
	public Boolean createOtherIn(Otherinspect inspect, List<OtherInspectDetail> otherInList, String userName) {
		String inspectBillNo = inspect.getBillNo();//检验单号
		String weightNo = inspect.getWeightNo();//称重申请单号
		List<StkOtherInDeatil> otherList = new ArrayList<>();
		StkOtherIn stkOtherIn = new StkOtherIn();
		String billNo = IXqcConst.createBillNo(BillType.CGRK);

		for (OtherInspectDetail detail : otherInList){
			StkOtherInDeatil  otherInDeatil = new StkOtherInDeatil();
			//详情数据
			otherInDeatil.setBillNo(billNo);
			otherInDeatil.setMaterialNo(detail.getMaterialNo());
			otherInDeatil.setMaterialName(detail.getMaterialName());
			otherInDeatil.setSpecification(detail.getSpecification());
			otherInDeatil.setBasicUnitName(detail.getUnitName());
			otherInDeatil.setBasicUnitNo(detail.getUnitNo());
			otherInDeatil.setLot(detail.getFlot());
			otherInDeatil.setQty(detail.getQualifiedQty());//实收数量为检验单的合个数量
			otherInDeatil.setStockNo(detail.getStockNo());
			otherInDeatil.setStockName(detail.getStockName());
			otherList.add(otherInDeatil);
		}
		stkOtherIn.setBillNo(billNo);
		stkOtherIn.setWeightNo(weightNo);
		stkOtherIn.setDate(new Date());
		stkOtherIn.setOrgNo(inspect.getOrgNo());
		stkOtherIn.setOrgName(inspect.getOrgName());
		stkOtherIn.setDeptNumber(inspect.getDeptNumber());
		stkOtherIn.setStatus("save");

		boolean inRes = stkOtherInService.save(stkOtherIn);
		boolean detailRes = stkOtherInDeatilService.saveOrUpdateBatch(otherList);

		//给库管发送待办通知
		try {
			Map<String,Object> data = new HashMap<>();
			data.put("billNo",billNo);
			yzjService.sendMsgToWare(data,BillType.QTRK.label());
		} catch (Exception e){
			_logger.info(e.getMessage());
		}
		return inRes && detailRes;
	}
	/**
	 * 查询仓库集合
	 * @return
	 */
	private List<Map<String,Object>> selectStcokList() throws Exception{
		VtuzxKingdeeCloudClient client = vtuzxKingdeeService.loginKingdee();
		List<Map<String,Object>> dataList = new ArrayList<>();
		//查询物料是够启用批号
		List<VtuzxMap> materialQuery = vtuzxKingdeeService.query(client, "BD_STOCK", new VtuzxArrayList<>(
						"FName",
						"FNumber"
				),
				"", null, 0, 0);
		if (!VtuzxUtil.isEmpty(materialQuery)) {
			for (VtuzxMap data : materialQuery){
				Map<String,Object> map =new HashMap<>();
				String fname = VtuzxUtil.getString(data,"FName");
				String FNumber = VtuzxUtil.getString(data,"FNumber");
				map.put("value",FNumber);
				map.put("text",fname);
				dataList.add(map);
			}
		}
		return dataList;
	}

	/**
	 * 判断仓库是否启用仓位
	 * @param stockNo
	 * @return
	 */
	private Boolean stockIsLoc(String stockNo) throws Exception{
		VtuzxKingdeeCloudClient client = vtuzxKingdeeService.loginKingdee();
		Boolean FIsOpenLocation = false;
		//查询物料是够启用批号
		List<VtuzxMap> materialQuery = vtuzxKingdeeService.query(client, "BD_STOCK", new VtuzxArrayList<>(
						"FIsOpenLocation"//是否启用仓位
				),
				String.format("FNumber = '%s'", stockNo), null, 0, 1);
		if (!VtuzxUtil.isEmpty(materialQuery)) {
			FIsOpenLocation = VtuzxUtil.getBoolean(materialQuery.get(0),"FIsOpenLocation");
		}
		return FIsOpenLocation;
	}

	/**
	 * 查询仓库向下的仓位信息
	 * @param stockNo
	 * @return
	 */
	private List<String> getlocationList(String stockNo) throws Exception{
		VtuzxKingdeeCloudClient client = vtuzxKingdeeService.loginKingdee();
		List<String> dataList = new ArrayList<>();
		//查询物料是够启用批号
		List<VtuzxMap> materialQuery = vtuzxKingdeeService.query(client, "BD_STOCK", new VtuzxArrayList<>(
						"FFlexEntryId.fnumber",//仓位编码
						"FFlexEntryName"//仓位名称
				),
				String.format("FNumber = '%s'", stockNo), null, 0, 0);
		if (!VtuzxUtil.isEmpty(materialQuery)) {
			for (Map<String,Object> data : materialQuery){
				String locationNo = VtuzxUtil.getString(data,"FFlexEntryId.fnumber");
//				String locationName = VtuzxUtil.getString(data,"FFlexEntryName");
//				Map<String,Object> locMap = new HashMap<>();
//				locMap.put("value",locationNo);
//				locMap.put("text",locationName);
				dataList.add(locationNo);
			}

		}
		return dataList;
	}
}